import type { Router } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import StorageService from '@/services/storage';
import { useAppStore } from '@/stores/app';
import { useAuthStore } from '@/stores/auth';
import { getUserinfo } from '@/modules/app-gateway';
import { ensureRoutesData } from './router-tools';
import config, { LOCALSTORAGE_USERINFO } from '@/config';
/**
 *
 * 路由守卫
 *
 */
export const useRouterGuard = (router: Router) => {
  router.beforeEach(async (to, from, next) => {
    // 统一路由拦截器
    NProgress.start();
    const appStore = useAppStore();
    const authStore = useAuthStore();
    // 未处理动态路由，先处理菜单数据
    if (authStore.token) {
      // 已登录: 用户信息
      const user = StorageService.getLocal(LOCALSTORAGE_USERINFO);
      if (!user) await getUserinfo();
      let isRouteTouched = false;
      if (!appStore.dynamicRoutesState) {
        // 动态注册路由
        await ensureRoutesData(router);
        isRouteTouched = true;
      }
      let _toRoute: any = undefined;
      if (isRouteTouched) {
        _toRoute = { ...to, replace: true };
      }
      // 已登录： 访问登录页面，重定向到首页
      if (to.path === '/login') {
        _toRoute = { name: 'AppIndex' };
      }
      console.log('router', router, _toRoute);
      next(_toRoute);
    } else {
      // 未登录
      const whiteList = config.route.whiteList;
      if (whiteList.includes(to.path)) {
        return next();
      } else {
        // 不能加redirect 否则登录无法正常返回
        return next('/login');
      }
    }
  });

  router.afterEach((to) => {
    NProgress.done();
  });
};
